/**********************************************************************
 * 
 * 若终端不存在 则新建终端  绑定终端和经销商的关系
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
         data:{
	
			dealer:1234 经销商编码

			terminalId:  SF 客户 Id 

			terminalName: 终端客户名称

			city :终端城市
         }
    }
*************************************************************************/
@RestResource(urlMapping='/CRM/upsertAccountForOrder')
global with sharing class UpsertAccountForOrder {
    @HttpPost
    global static RestReturnMessage doPost(Map<String,String>data ) {

    	try {

    		if(		data == null 
    			|| data.isEmpty() 
    			|| !data.containsKey('dealer') )throw new DmlException('参数异常!');
    	    

    	    List<Account> dealers = [select Id from Account where AccountNumber =:data.get('dealer')];
    		if(dealers.isEmpty() )throw new DmlException('CRM 中未找到经销商:'+data.get('dealer'));

    		Account acc = null;
    		if(String.isNotBlank(data.get('terminalId'))){

    			 List<Account> accs = [select Id ,Name ,AccountNumber from Account where Id=:data.get('terminalId') limit 1 ];

    			 if(accs.isEmpty())throw new DmlException('CRM 中未找到客户:'+data.get('terminalId'));

    			 //terminalId = accs.get(0).Id;
    			 acc = accs.get(0);

    		}else{//新建客户

    			if(!data.containsKey('terminalName') || 
    				!data.containsKey('city')) throw new DmlException('新加客户信息不全');
    			 acc = new Account();
    			acc.Name = data.get('terminalName') ;
                
                acc.AccountSource = 'ForOrder';

    			String city = '%'+data.get('city') +'%';

    			List<City__c> ps  = [select Id ,Province__c from City__c where Name like: city ];
    			if(ps.isEmpty() ) throw new DmlException('未匹配到城市:'+city);
    			acc.Province__c = ps.get(0).Province__c;
    			acc.City__c  = ps.get(0).Id;
    		

    			
    		}
    		SavePoint sp = Database.setSavepoint();
			try {

				if(acc.Id == null )insert acc;
			    MajorUserInfo__c mu = new MajorUserInfo__c();
			    mu.Dealer__c = dealers.get(0).Id;
			    mu.MajorCustomer__c = acc.Id;
                mu.BackgroundImport__c = true;
			    insert mu;

			    List<Map<String,String>>res = new List<Map<String,String>>();
			    res.add(transData(acc));
			    return Utils.getRestReturnMessage(true, 'success',res);

			}catch (Exception  e) {
			    Database.rollback(sp);
			    throw e;
			}
    	
    	}
    	catch (Exception e) {
    	    
			return Utils.getRestReturnMessage(false, e.getMessage(),new List<Map<String,String>>());

    	}
    	

    }
    private static Map<String,String> transData(Account mu ){
    	
    	Map<String,String>  m = new Map<String,String> ();
    	m.put('Id',mu.Id);
    	m.put('Name',mu.Name);
    	m.put('AccountNumber',mu.AccountNumber);

    	m.put('Belong','false' );
    	return m;

    }
}